<?php

	class ImageUtility {

		private function __construct() {}

		public static function getScaledImage( $imageIdOrUri, $width = false, $height = false ) {
			try {
				$image = getMultiple( 'image', (is_numeric( $imageIdOrUri ) ? "imageId||$imageIdOrUri" : "uri||$imageIdOrUri" ));
				if( $image->getResultCount() < 1 ) {
					return '';
				}
				if( $width == false ) {
					return S3_IMAGE_PUBLIC_LOCATION . $image->getUri();
				}
				if( $height === false ) {
					$height = ( int ) ( ( $width * $image->getHeight() ) / $image->getWidth() );
				}
				if( $image->getWidth() == $width && $image->getHeight() == $height ) {
					return S3_IMAGE_PUBLIC_LOCATION . $image->getUri();
				}
			
				$imageDimension = getMultiple( 'imageDimension', 'imageId||' . $image->getImageId(), "width||$width", "height||$height" );
				if( $imageDimension->getResultCount() > 0 ) {
					return S3_IMAGE_PUBLIC_LOCATION . $imageDimension->getUri();
				}
				
				$arrFilePath = pathinfo( $image->getUri() );
				$dirname = $arrFilePath[ 'dirname' ];
				$basename = $arrFilePath[ 'basename' ];
				$extension = $arrFilePath[ 'extension' ];
				$filename = $arrFilePath[ 'filename' ];
				
				$scaledName =  $filename. '_' . $width . 'x' . $height . '.' . $extension;
				$path = $dirname . '/';
					
				// download original and process it
				$imgTempPath = self::downloadAmazonMedia( $image->getUri(), $extension );
				if( $imgTempPath == '' ){
					continue;
				}
				
				$scaledImagePath = self::resizeImage( $imgTempPath, $extension, $width, $height );
				$uploadResult = self::uploadAmazonMedia( $scaledImagePath, $scaledName, $image->getMimetype(), $path );
				
				if( $uploadResult ) {
					@unlink( $imgTempPath );
					@unlink( $scaledImagePath );
					
					$scaledUri = $path . $scaledName;
					if( getMultiple( 'imageDimension', "uri||$scaledUri" )->getResultCount() > 0 ) {
						return S3_IMAGE_PUBLIC_LOCATION . $scaledUri;
					}

					$imageDimension = getDb( 'imageDimension', 'add' );
					$imageDimension->set( 'imageId||' . $image->getImageId(), "uri||$scaledUri", "width||$width", "height||$height" );
					return S3_IMAGE_PUBLIC_LOCATION . $scaledUri;
				} else {
					return '';
				}
			} catch( Exception $ex ) {
				return '';
			}
		}
		
		public static function getCroppedImage( $imageIdOrUri, $cropDimension ) {
			try {
				$image = getMultiple( 'image', (is_numeric( $imageIdOrUri ) ? "imageId||$imageIdOrUri" : "uri||$imageIdOrUri" ));
				if( $image->getResultCount() < 1 ) {
					return '';
				}
				
				$arrFilePath = pathinfo( $image->getUri() );
				$dirname = $arrFilePath[ 'dirname' ];
				$basename = $arrFilePath[ 'basename' ];
				$extension = $arrFilePath[ 'extension' ];
				$filename = $arrFilePath[ 'filename' ];
				
				$arrCropDimension = json_decode( $cropDimension, true );
				
				$imageX = isset( $arrCropDimension[ 'x' ] ) ? (int)  $arrCropDimension[ 'x' ] : 0;
				$imageY = isset( $arrCropDimension[ 'y' ] ) ? (int)  $arrCropDimension[ 'y' ] : 0;
				$imageW = isset( $arrCropDimension[ 'w' ] ) ? (int)  $arrCropDimension[ 'w' ] : 140;
				$imageH = isset( $arrCropDimension[ 'h' ] ) ? (int)  $arrCropDimension[ 'h' ] : 140;
				
				$cropPostfix = 'x' . $imageX . 'y' . $imageY . 'w' . $imageW . 'h' . $imageH;
				
				$croppedName =  $filename. '_' . $cropPostfix . '.' . $extension;
				$path = $dirname . '/';
				
				$objCroppedImage = getMultiple( 'image', 'uri||' . $croppedName, 'width||' . $imageW, 'height||' . $imageH );
				if( $objCroppedImage->getResultCount() > 0 ) {
					return $objCroppedImage->getUri();
				}
				
				// download original and process it
				$imgTempPath = self::downloadAmazonMedia( $image->getUri(), $extension );
				if( $imgTempPath == '' ){
					continue;
				}
				
				$croppedImagePath = self::cropImage( $imgTempPath, $extension, $imageX, $imageY, $imageW, $imageH );
				$size = filesize($croppedImagePath);
				$uploadResult = self::uploadAmazonMedia( $croppedImagePath, $croppedName, $image->getMimetype(), $path );
		
				if( $uploadResult ) {
					@unlink( $imgTempPath );
					@unlink( $croppedImagePath );
						
					$croppedUri = $path . $croppedName;
					if( getMultiple( 'image', "uri||$croppedUri" )->getResultCount() > 0 ) {
						return $croppedUri;
					}
					
					// add the image entry into image table
					$imageAddObj = getDb( 'image', 'add' );
					$imageAddObj->set( 'uri||' . $croppedUri, 'title||' . $image->getTitle(), 'width||' . $imageW,
							'height||' . $imageH, 'mimetype||' . $image->getMimetype(), 'size||' . $size);
					return $croppedUri;
					
				} else {
					return '';
				}
			} catch( Exception $ex ) {
				return '';
			}
		}
		
		public static function uploadImageFromS3PrivateUrl( $imageUrl ) {
			try{
				$arrFilePath = pathinfo( $imageUrl );
				$dirname = $arrFilePath[ 'dirname' ];
				$basename = $arrFilePath[ 'basename' ];
				$extension = $arrFilePath[ 'extension' ];
				$filename = $arrFilePath[ 'filename' ];
				
				$imgTempPath = ImageUtility::downloadAmazonMedia( $imageUrl, $extension );
				if( $imgTempPath == '' ){
					continue;
				}
				
				$exif = getFileExifData( $imgTempPath );
				$fileSize = $exif['FileSize'];
				$mimeType = $exif['MimeType'];
				$width = $exif['COMPUTED']['Width'];
				$height = $exif['COMPUTED']['Height'];
				
				$newFileName =  $filename. '.' . $extension;
				
				$path = S3_IMAGE_BUCKET . date( 'Y/m/' );
				
				$uploadResult = self::uploadAmazonMedia( $imgTempPath, $newFileName, $mimeType, $path );
				if( $uploadResult ) {
					@unlink( $imgTempPath );
					$imageData = array( 'path' => $path . $newFileName, 'filename' => $newFileName, 'size' => $fileSize,
							'width' => $width, 'height' => $height, 'mimetype' => $mimeType );
					$imagePath = ImageUtility::saveFilepickerImagePath( $imageData );
					return $imagePath;
				}
			}catch( Exception $ex ){
				//describe($ex, true);
				throw $ex;
			}
		}

		public static function uploadImageFromUrl( $imageUrl ) {
			try{
				$imgTempPath = self::downloadImageFromUrl( $imageUrl );
				if( $imgTempPath == '' ){
					return false;
				}
				$exif = getFileExifData( $imgTempPath );
				$fileSize = $exif['FileSize'];
				$mimeType = $exif['MimeType'];
				$width = $exif['COMPUTED']['Width'];
				$height = $exif['COMPUTED']['Height'];
				
				$newFileName =  'userimg_' . randomStringGenerator(15, true). '.jpg';
				
				$path = S3_IMAGE_BUCKET . date( 'Y/m/' );
				
				$uploadResult = self::uploadAmazonMedia( $imgTempPath, $newFileName, $mimeType, $path );
				if( $uploadResult ) {
					@unlink( $imgTempPath );
					$imageData = array( 'path' => $path . $newFileName, 'filename' => $newFileName, 'size' => $fileSize,
							'width' => $width, 'height' => $height, 'mimetype' => $mimeType );
					$imagePath = ImageUtility::saveFilepickerImagePath( $imageData );
					return $imagePath;
				}
			}catch( Exception $ex ){
				//describe($ex, true);
				throw $ex;
			}
		}
		
		public static function downloadAmazonMedia( $mediaPath, $extension ){
			try{
				$libImageObj = Image::getInstance( AMAZON_ID, AMAZON_SECRET_KEY, S3_BUCKET );
				return $libImageObj->downloadPrivateFile( $mediaPath, $extension );
			}catch( Exception $ex ){
				throw $ex;
			}
		}

		public static function downloadImageFromUrl( $url ){
			try{
				$libImageObj = Image::getInstance( AMAZON_ID, AMAZON_SECRET_KEY, S3_BUCKET );
				return $libImageObj->downloadImageFromUrl( $url );
			}catch( Exception $ex ){
				throw $ex;
			}
		}
		
		public static function deleteS3File( $filePath ){
			try{
				$libImageObj = Image::getInstance( AMAZON_ID, AMAZON_SECRET_KEY, S3_BUCKET );
				return $libImageObj->deleteFileFromS3( $filePath );
			}catch( Exception $ex ){
				throw $ex;
			}
		}

		public static function uploadAmazonMedia( $sourceFilePath, $fileName, $path = false, $access = 'public-read' ){
			$libImage = Image::getInstance( AMAZON_ID, AMAZON_SECRET_KEY, S3_BUCKET );
			return $libImage->saveFileOnS3( $sourceFilePath, $fileName, $path, $access );
		}
		
		public static function resizeImage( $mediaPath, $extension, $width, $height ){
			try{
				$tempFile = 'tempfile_' . randomStringGenerator(7, true) . '.' . $extension;
				
				/*$imgTempPathLayer = ImageWorkshop_ImageWorkshop::initFromPath( $mediaPath );
				$imgTempPathLayer->resizeInPixel($width, $height, false);
				$imgTempPathLayer->save( PUBLIC_PATH . 'temp_files', $tempFile, false, null, 95 );
				return PUBLIC_PATH . 'temp_files' . DIRECTORY_SEPARATOR . $tempFile;*/

				$savePath = PUBLIC_PATH . 'temp_files' . DIRECTORY_SEPARATOR . $tempFile;
				require_once( FRAMEWORK_PATH . implode( DIRECTORY_SEPARATOR, array( 'phpthumb', 'ThumbLib.inc.php' ) ) );
				$ignoreAspectRatio = true;
				$thumb = PhpThumbFactory::create($mediaPath, array('resizeUp' => true));
				$ignoreAspectRatio ? $thumb->adaptiveResize($width, $height) : $thumb->resize($width, $height);
				$thumb->save( $savePath );
				return $savePath;
			}catch( Exception $ex ){
				throw $ex;
			}
		}
		
		public static function cropImage( $mediaPath, $extension, $imageX, $imageY, $imageW, $imageH ){
			try{
				$tempFile = 'tempfile_' . randomStringGenerator(7, true) . '.' . $extension;
		
				$imgTempPathLayer = ImageWorkshop_ImageWorkshop::initFromPath( $mediaPath );
				$imgTempPathLayer->cropInPixel( $imageW, $imageH, $imageX, $imageY, "LT" );
				$imgTempPathLayer->save( PUBLIC_PATH . 'temp_files', $tempFile, false, null, 95 );
				return PUBLIC_PATH . 'temp_files' . DIRECTORY_SEPARATOR . $tempFile;
		
			}catch( Exception $ex ){
				throw $ex;
			}
		}
		
		
		
	}